<template>
  <el-form label-width="100px">
    <el-form-item label="SPU 名称"> SPU 名称</el-form-item>
    <el-form-item label="SKU 名称">
      <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input type="number" v-model="skuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input type="number" v-model="skuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" placeholder="规格描述" rows="4" v-model="skuInfo.skuDesc"></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item :label="attr.attrName" v-for="attr in attrList" :key="attr.id">
          <el-select placeholder="请选择" v-model="attr.attrIdValueId">
            <el-option :value="`${item.attrId}:${item.id}`" :label="item.valueName" v-for="item in attr.attrValueList"
                       :key="item.id" />
          </el-select>
        </el-form-item>

      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item v-for="attr in saleAttrList" :label="attr.saleAttrName" :key="attr.id">
          <el-select placeholder="请选择" v-model="attr.attrIdAttrValueId">
            <el-option :value="`${item.baseSaleAttrId}:${item.id}}`" v-for="item in attr.spuSaleAttrValueList"
                       :label="item.saleAttrValueName" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="图片列表">
      <el-table :data="spuImgList" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片" prop="imgUrl">
          <template v-slot="{row}">
            <img height="120" :src="row.imgUrl" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-tag v-if="row.isDefault==='1'">默认图片</el-tag>
            <el-button v-else type="primary" @click="changeDefault(row)">设为默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button type="default" @click="emit('setState',2)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SkuForm"
});
</script>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import useAttrStore from "@/stores/attr";
import {
  requestSpuSaleAttrList,
  requestSpuImgList,
  type spuImageListType,
  type spuInfoType,
  type spuSaleAttrListType
} from "@/api/spu";
import {
  type skuInfoItemType,
  type skuImageItemType,
  type skuImageListType,
  type skuAttrValueListType,
  type skuSaleAttrValueListType,
  type skuAttrValueItemType,
  requestSaveSkuInfo,
} from "@/api/sku";
import { type attrListItemType, type attrListType, requestAttrList } from "@/api/Attr";
import { ElMessage } from "element-plus";

/**@skuInfo 初始化收集数据*/
const skuInfo = ref<skuInfoItemType>({
  //需要我们直接进行双向绑定收集
  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",
  //需要从props中的spu中直接拿的数据
  spuId: 0,
  tmId: 0,
  category3Id: 0,
  //需要计算收集的
  skuDefaultImg: "",
  //需要计算收集的数据
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: []
});

//1.接受props传值
const props = defineProps<{
  spuInfo: spuInfoType;
}>();
const spuInfo = props.spuInfo;

//2.接受自定义事件,用来切换组件
const emit = defineEmits<{
  (event: "setState", state: number, row?: spuInfoType): void;
}>();

//3.拿到pinia中的三级分类数据
const attrStore = useAttrStore();
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

//4.获取所有的平台属性
const attrList = ref<attrListType>([]);
const saleAttrList = ref<spuSaleAttrListType>([]);
const spuImgList = ref<spuImageListType>([]);
/**@getInitData 初始化数据获取的请求*/
const getInitData = async () => {
  //获取所有的平台属性 requestAttrList(1id,2id,3id)==>attrListType
  const promise1 = requestAttrList({
      category1Id: category1Id.value as number,
      category2Id: category2Id.value as number,
      category3Id: category3Id.value as number
    }
  );
  //获取所有销售属性 requestSpuSaleAttrList()===>spuSaleAttrListType
  const promise2 = requestSpuSaleAttrList(spuInfo.id as number);
  //根据当前的spuId获取所有图片列 requestSpuImgList(spuId)===>SpuImgListType
  const promise3 = requestSpuImgList(spuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);
  attrList.value = result[0];
  saleAttrList.value = result[1];
  spuImgList.value = result[2];
};

onMounted(() => {
  //发送初始化请求
  getInitData();
});

//5.收集我们选中的平台属性
/*
  收集的时候只需要某些下垃菜单的
  attrId?:number;//就是平台属性具体某一个下垃数据的attrId
  valueId?:number;//就是平台属性具体某一个下垃数据的id
  //下边都是不需要的
  id?: number;
  skuId?: number;
  attrName?: string;
  valueName?: string;
*/

//6.收集选中的销售属性
/*
 收集需要的数据是：
 saleAttrValueId?:number;
 saleAttrId?:number;
 //不需要
 id?: number;
 skuId?: number;
 spuId?: number;
 saleAttrName?: string;
 saleAttrValueName?: string;
 */

//7.收集sku图片
/*
  imgName: string;
  imgUrl: string;
  spuImgId?: number;
  isDefault?: string;
  //不需要的
  id?: number;
    skuId?: number;
*/

interface imgListType {
  id: number;
  imgName: string;
  imgUrl: string;
  spuId: number;
}

//定义一个数据，收集选中的图片组成的数据（不能改变原数组，因为原数组的初始化用来展示的）
const skuImgList = ref<spuImageListType>([]);
const handleSelectionChange = (val: imgListType[]) => {
  skuImgList.value = val;
};

//设置图片默认的按钮
const changeDefault = (row: skuImageItemType) => {
  spuImgList.value.forEach(item => {
    item.isDefault = "0";
  });
  row.isDefault = "1";
};

//提交
const saveData = async () => {
  //1.将props传递过来的spuInfo的数据收集到skuInfo中
  skuInfo.value.spuId = spuInfo.id;
  skuInfo.value.tmId = spuInfo.tmId as number;
  skuInfo.value.category3Id = spuInfo.category3Id;

  //2.收集当前组件中的其他属性
  // 收集平台属性
  attrList.value.forEach(item => {
    if (item.attrIdValueId) {
      const newAttr = {
        attrId: +item.attrIdValueId?.split(":")[0],
        valueId: +item.attrIdValueId?.split(":")[1]
      };
      (skuInfo.value.skuAttrValueList as skuAttrValueListType).push(newAttr);
    }
  });


  //收集销售属性
  saleAttrList.value.map(item => {
    if (item.attrIdAttrValueId) {
      const [saleAttrId, saleAttrValueId] = item.attrIdAttrValueId.split(":");
      const newSaleAttr = {
        saleAttrId: +saleAttrId,
        saleAttrValueId: +saleAttrValueId
      };
      (skuInfo.value.skuSaleAttrValueList as skuSaleAttrValueListType).push(newSaleAttr);
    }
  });


  //收集图片数据
  skuImgList.value.forEach(item => {
    const newImgList = {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id,
      isDefault: item.isDefault
    };
    //设置默认图片
    if(item.isDefault==='1'){
      skuInfo.value.skuDefaultImg=item.imgUrl
    }
    //将图片插入列表
    (skuInfo.value.skuImageList as skuImageListType).push(newImgList);
  });


  try {
    //发起保存sku信息的请求
    await requestSaveSkuInfo(skuInfo.value);
    ElMessage.success("新增sku成功");
    emit("setState", 0);
  } catch (e) {
    ElMessage.error("新增sku失败");
  }
};
</script>
